#!/bin/bash
component_name=$1

git_url=$2

version=$3

repo_name=$4
repo_url=$5

export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
export LC_ALL=en_US.UTF-8

CURRENT_USER=`whoami`

USER_DIR=/Users/${CURRENT_USER}


base_path=${USER_DIR}/iPack/iOS/Components
# 拉去代码
# component_path=base_path/${component_name}

if [ ! -d $base_path/${component_name} ];
then
  cd $base_path
  git clone $git_url
  if [ $? != 0  ]
  then
    echo '拉取代码失败'
    exit 1
  fi
  cd $base_path/${component_name}
else
  cd $base_path/${component_name}
  git checkout .
  if [ $? != 0  ]
  then
    echo '拉取代码失败'
    exit 1
  fi
  git pull
  if [ $? != 0  ]
  then
    echo '拉取代码失败'
    exit 1
  fi
fi

# 升级tag

git config user.email "admin@ipack.com"
git config user.name "iPack"

# 获取最后的tag
current_tag=`git describe --tags \`git rev-list --tags --max-count=1\``
# current_tag=$version
if [ $current_tag != $version ]; then
    echo '版本信息异常(数据库中版本:'$version',代码库中版本:'$current_tag
    exit 1
fi

current_tag_1=`echo $current_tag | cut -d \. -f 1`
current_tag_2=`echo $current_tag | cut -d \. -f 2`
current_tag_3=`echo $current_tag | cut -d \. -f 3`

current_tag_3=$[$current_tag_3+1]

update_tag=${current_tag_1}'.'${current_tag_2}'.'${current_tag_3}

echo '当前版本：'${current_tag}'，即将升级到'${update_tag}

file=`find ./ -maxdepth 1 -name "${component_name}*spec*"`
echo '查看到描述文件: '$file
sed -i '' "s/$current_tag/$update_tag/g" "$file"

git add $file

git commit -m "Commit by iPack,update to ${update_tag}"

git push

git tag -m "tag by iPack" ${update_tag}
git push --tags

n_current_tag=`git describe --tags \`git rev-list --tags --max-count=1\``

echo 'ipack-version|'${n_current_tag}

if [ $n_current_tag != $update_tag ]; then
  echo ${n_current_tag}'|'
  echo ${update_tag}'|'
  echo ${n_current_tag} ' not equal to ' ${update_tag}
  exit 1
fi

`echo "2.3" > .swift-version`

# 检查问题
/usr/local/bin/pod lib lint --allow-warnings --verbose --sources="${repo_url},https://github.com/CocoaPods/Specs.git"
if [ $? != 0  ]
then
  echo '检查代码出现问题'
  exit 1
fi

hui=`/usr/local/bin/pod repo list |grep $repo_name`
echo $hui
if [ "$hui" = "" ]; then
    /usr/local/bin/pod repo add ${repo_name} ${repo_url}
    echo "Finish add ${repo_name} to .cocoapod"
else
    echo "Already has ${repo_name} in .cocoapod"
fi

/usr/local/bin/pod repo push ${repo_name} $file --allow-warnings --verbose
if [ $? != 0  ]
then
  echo '提交到版本库出现异常'
  exit 1
fi
exit 0
